// 监听来自content script的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('Background script received message:', message);

  if (message.action === 'captureTab') {
    console.log('Capturing tab screenshot');
    
    // 确保在发送响应之前不会关闭消息端口
    const captureTab = async () => {
      try {
        const dataUrl = await chrome.tabs.captureVisibleTab(null, { format: 'png' });
        console.log('Screenshot captured successfully');
        sendResponse({ dataUrl: dataUrl });
      } catch (error) {
        console.error('Screenshot capture failed:', error);
        sendResponse({ error: error.message });
      }
    };

    captureTab();
    return true; // 表示我们将异步发送响应
  }
});
